package com.alen.websocketDemo

import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.TextView

class MessageAdapter(var context: Context, var data: MutableList<MessageData>) : BaseAdapter() {

    override fun getCount(): Int {
        return data.size
    }

    override fun getItem(position: Int): MessageData {
        return data[position]
    }

    override fun getItemId(position: Int): Long {
        return position.toLong()
    }

    override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
        var rootView: View? = convertView
        val data = getItem(position)
        var viewHolder: ViewHolder? = null
        if (rootView == null) {
            rootView = LayoutInflater.from(context).inflate(R.layout.item_message, null, false)
            viewHolder = ViewHolder(rootView)
            rootView!!.tag = viewHolder
        } else {
            viewHolder = rootView.tag as ViewHolder
        }
        viewHolder.tvName.text = data.name
        viewHolder.tvContent.text = data.content
        return rootView!!
    }

    fun addData(item: MessageData) {
        data.add(item)
        notifyDataSetChanged()
    }

    class ViewHolder(contentView: View) {
        var tvName: TextView
        var tvContent: TextView

        init {
            tvName = contentView.findViewById(R.id.tvName)
            tvContent = contentView.findViewById(R.id.tvContent)
        }

    }

}